package com.hezhiqin.netty.rpc.registrytozk;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

/**
 * @program: homeWork
 * @description:
 * @author: hezhiqin
 * @create: 2020-01-19 15:19
 */
public class RegistryWithZK implements IRegistryCenter {

    public  static  final  String CONNECTION_STR ="192.168.223.128:2181,192.168.223.129:2181,192.168.223.130:2181";

    CuratorFramework framework = null;

   {
        framework = CuratorFrameworkFactory.builder()
                .connectString(CONNECTION_STR)
                .sessionTimeoutMs(1000)
                .retryPolicy(new ExponentialBackoffRetry(1000,3)).namespace("registry").build();
        framework.start();
    }

    public void registry(String serviceName, String serviceAddr) {
        String servicePath="/"+serviceName;
        System.out.println("framework"+framework);
        try {
            //判断节点是否存在
            if(framework.checkExists().forPath(servicePath)==null){
                framework.create().creatingParentsIfNeeded().
                        withMode(CreateMode.PERSISTENT).forPath(servicePath);
            }
            //serviceAddress: ip:port
            String addressPath=servicePath+"/"+serviceAddr;
            framework.create().withMode(CreateMode.PERSISTENT).forPath(addressPath);
            System.out.println("服务注册成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
